# coding:utf-8
# coder:DongLing

# 爬取
# url = 'http://tieba.baidu.com/p/2460150866'
# 前三页所有的图片

import requests
import re
from urllib.request import urlretrieve
import time
from os import path
import os

num = 1
# 获取网页源代码
def get_code(url):
    try:
        page = requests.get(url)
        return page.text
    except Exception as e:
        print(e)


# 获取源代码里面的图片
def get_image(code):
    try:
        # 使用正则匹配图片链接地址
        reg = r'src="(.+?\.jpg)" pic_ext'  # 匹配规则
        image = re.compile(reg)
        image_list = re.findall(image, code)
        # 图片名字
        global num
        # 遍历列表获取每一个图片的链接
        for url in image_list:
            # 拿到每一个图片的链接地址并下载
            if path.exists(r'./image/'):
                pass
            else:
                os.makedirs('./image/')

            urlretrieve(url, './image/'+'%s.jpg' % num)  # 下载，保存
            num += 1
            time.sleep(1)
    except Exception as e:
        print(e)


if __name__ == '__main__':
    pn = 1
    while pn < 4:
        # 获取源代码
        url = 'http://tieba.baidu.com/p/2460150866?pn=%s' % pn
        html = get_code(url)
        # 获取图片
        get_image(html)
        print('图片处理完毕')
        pn += 1
